﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Gasco.Business.Services;
using Gasco.DataAccess;

public partial class Controls_origin_index : System.Web.UI.UserControl
{
    private IProductService productService;

    public IProductService ProductService {
        get
        {
            if (productService == null)
                productService = new ProductService();

            return productService;
        }
   }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            GetOrigins(null, 1, true, gvOrigins.SortExpression, gvOrigins.SortDirection.ToString());
    }

    private void GetOrigins(string keyword, int pageNumber, bool setPageCount, string sortBy, string desc)
    {
        ViewState["CurrentPage"] = pageNumber;

        if (setPageCount)
            gvOrigins.VirtualItemCount = ProductService.CountSearchOrigins(keyword);

        gvOrigins.DataSource = ProductService.SearchOrigins(keyword, gvOrigins.PageSize, pageNumber, sortBy, desc);
        gvOrigins.DataBind();
    }

    protected void gvOrigin_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (ViewState["sort"] == null || ViewState["sort"].ToString() == "asc")
        {
            e.SortDirection = SortDirection.Descending;
            ViewState["sort"] = "desc";
        }
        else
        {
         e.SortDirection = SortDirection.Ascending;
         ViewState["sort"] = "asc";
        }
        
        GetOrigins(tbSearch.Text, gvOrigins.PageIndex + 1, false, e.SortExpression, e.SortDirection.ToString());
    }

    protected void lbSearch_Click(object sender, EventArgs e)
    {
        GetOrigins(tbSearch.Text, 1, true, gvOrigins.SortExpression, gvOrigins.SortDirection.ToString());
    }

    
    protected void gvOrigins_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvOrigins.PageIndex = e.NewPageIndex;
        GetOrigins(tbSearch.Text,e.NewPageIndex + 1, false,gvOrigins.SortExpression,gvOrigins.SortDirection.ToString());
    }

    protected void gvOrigins_Deleting(object sender, GridViewDeleteEventArgs e)
    {
        ProductService service = new ProductService();
        service.DeleteOrigin(Convert.ToInt32(gvOrigins.DataKeys[e.RowIndex].Value));
        GetOrigins(tbSearch.Text,1,true,gvOrigins.SortExpression,gvOrigins.SortDirection.ToString());
    }

}
